package com.kuang.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/**
 * @author wgw1206798585@vip.qq.com
 * @version 1.0
 * @date 2020-03-12 21:15
 */
@RestController
public class JdbcController {
    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    @RequestMapping("/userList")
    public List<Map<String, Object>> userList() {
        String sql = "select *\n" +
                "from user;";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);
        return list_maps;
    }

    //添加一个用户
    @RequestMapping("/addUser")
    public String addUser() {
        String sql = "insert into user (id, name, pwd)\n" +
                "values (6,'咖啡','7777777');";
        jdbcTemplate.update(sql);
        return "add_ok";
    }

    //修改一个用户
    @RequestMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id) {
        String sql = "update user set name = ?,pwd =? where id =" + id;
        //封装一个对象
        Object[] objects = new Object[2];
        objects[0] = "小明22222222";
        objects[1] = "zzzzzzzzzzzz";

        jdbcTemplate.update(sql, objects);
        return "update_ok";
    }

    //删除一个用户
    @RequestMapping("/delUser/{id}")
    public String delUser(@PathVariable("id") int id) {
        String sql = "delete from user\n" +
                "where id=?";
        jdbcTemplate.update(sql, id);
        return "del_ok";
    }
}
